// pages/login/login.js
const app = getApp()

Page({
  data: {
    loading: false
  },

  onLoad() {
    // Check if already logged in
    const token = wx.getStorageSync('token');
    if (token && app.globalData.userInfo) {
      wx.redirectTo({
        url: '/pages/home/home'
      });
    }
  },

  handleLogin() {
    this.setData({ loading: true });
    
    wx.login({
      success: (res) => {
        console.log('wx.login res:', res); // 调试日志
        if (res.code) {
          console.log('获取到code:', res.code); // 确认code存在
          this.getSessionInfo(res.code);
        } else {
          wx.showToast({ title: '获取code失败:' + res.errMsg, icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('wx.login失败:', err); // 错误日志
        wx.showToast({ title: '登录调用失败', icon: 'none' });
      },
      complete: () => {
        this.setData({ loading: false });
      }
    });
  },

  getSessionInfo(code) {
    wx.request({
      url: `${app.globalData.baseUrl}/auth/wxSession`,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 根据后端要求设置
      },
      data: {
        code: code // 确保参数名与后端一致
      },
      success: (res) => {
        console.log('wxSession接口响应:', res);
        if (res.data.code === 200) {
          this.wxLogin(res.data.data);
        } else {
          this.setData({ loading: false });
          wx.showToast({
            title: '获取session失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        this.setData({ loading: false });
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  wxLogin(sessionInfo) {
    wx.request({
      url: `${app.globalData.baseUrl}/auth/wxLogin`,
      method: 'POST',
      data: {
        wxOpenId: sessionInfo.openid
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.setStorageSync('token', res.data.data);
          this.getUserInfo(res.data.data);
        } else {
          this.setData({ loading: false });
          wx.showToast({
            title: '登录失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        this.setData({ loading: false });
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  getUserInfo(token) {
    wx.request({
      url: `${app.globalData.baseUrl}/auth/userInfo`,
      header: {
        'Authorization': token
      },
      success: (res) => {
        this.setData({ loading: false });
        if (res.data.code === 200) {
          app.globalData.userInfo = res.data.data;
          wx.redirectTo({
            url: '/pages/home/home'
          });
        } else {
          wx.showToast({
            title: '获取用户信息失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        this.setData({ loading: false });
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  }
});
